import { platformsettingsService,Platformsettings } from './../../services/platformsettings.service';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, Validators } from '@angular/forms';
import { ToasterService } from 'app/modules/share/services/toaster.service';
import { RepositoryService } from '../../services/repository.service';
import { map } from 'rxjs/operators';
// import { Platformsettings } from '../../services/platformsettings.service';
import { kebabCase } from 'lodash';
//
@Component({
  selector: 'm-platformsetting',
  templateUrl: './platformsettings.component.html',
  styleUrls: ['./platformsettings.component.scss']
})
export class platformsettingComponent implements OnInit {
	constructor(
		private route: ActivatedRoute,
		private router: Router,
		private fb: FormBuilder,
		private toaster: ToasterService,
    private service: RepositoryService,
    private platformsetting: platformsettingsService
  ) {}
  

  isEditing:boolean= false
  tempData:any={
    secureSetting_cookie_max_valid_minutes:'',
      secureSetting_page_max_quiet_minutes:''
  }

  handleCancelbtnClick=function(){
    this.isEditing=!this.isEditing

    let obj={
      ...this.tempData
    }
    console.log('this.tempData---:',this.tempData,obj)
    this.repoForm.patchValue(obj);

    console.log('this.tempData---:',this.tempData)
    // this._data.secureSetting.cookie_max_valid_minutes=this._data.tempData.secureSetting_cookie_max_valid_minutes 
    // this._data.secureSetting.page_max_quiet_minutes=this._data.tempData.secureSetting_page_max_quiet_minutes 
}

  isInvalidNum=function(control:any){
    let max=this;
    // console.log('this in isInvalidNum:',this,typeof(this))
    // console.log('control---:',control,control.value)
    let v=control.value-0;
    return new Promise((resolve)=>{

      let isValid=(Number.isInteger(v) && v>=1 && v<=max)
      console.log('isValid--------:',isValid)

      if(isValid){
        resolve(null)
      }else{
        resolve({isInvalid:true})
      }

      
    })
    // return {isValid:(Number.isInteger(v) && v>=1 && v<=max)}
    // return !(Number.isInteger(v) && v>=1 && v<=max)
}

	repoForm = this.fb.group({
		// DeepinAppStoreUrl: ['', Validators.required],
    // DeepinAppStoreSourceList: [['']],
    // DeepinAppStoreIconUrl: [''],
    // DeepinAppStoreBackgroundUrl: [''],
    cookie_max_valid_minutes: ['', Validators.required,this.isInvalidNum.bind(44640)],
page_max_quiet_minutes: ['', Validators.required,this.isInvalidNum.bind(1440)]

	});
	// context$ = this.repoForm.valueChanges.pipe(map(value => this.preview(value)));



  
  


	async ngOnInit() {
    window['HACKER'].setGlobalVariableForViewModel.call(this)
    const resp = await this.platformsetting.getAppStore();
    const securtySetting:any = await this.platformsetting.getSecurtySetting();
    console.log('securtySetting---:',securtySetting)
    const appStoreConfigs: Partial<Platformsettings> = resp['message'];


//     cookie_max_valid_minutes: "200"
// page_max_quiet_minutes: "30"

    const formData = {//
      // ...this.getFormData(appStoreConfigs),
      ...securtySetting.body
    }

    this.tempData.cookie_max_valid_minutes = formData.cookie_max_valid_minutes 
    // this.tempData.secureSetting_cookie_max_valid_minutes = formData.cookie_max_valid_minutes 
    this.tempData.page_max_quiet_minutes = formData.page_max_quiet_minutes 
    // this.tempData.secureSetting_page_max_quiet_minutes = formData.page_max_quiet_minutes 

    console.log('formData', formData);
    console.log('formData----------------:',formData)
    this.repoForm.patchValue(formData);

  }

  async saveSecurtySetting(){

    if(this.repoForm.get('cookie_max_valid_minutes').hasError('isInvalid') || this.repoForm.get('page_max_quiet_minutes').hasError('isInvalid')){
        return false;
    }

    let fd=new FormData(),
    obj=this.repoForm.getRawValue();
    for(let i in obj){
        fd.append(i,obj[i])
    }

    try{
      this.isEditing=false
      // this.http.patch(`/api/admin/scene_config/${zid}`, formData).toPromise();
      let res = await window['$angularHttp'].client.patch(  '/api/admin/config/secure',fd).toPromise();
      
      window['$angularToast'].success('操作成功')
  
  
      this.tempData={
        ...this.repoForm.getRawValue()
      }
    }catch(e){
      this.handleCancelbtnClick()
    }

    

    // this.tempData.secureSetting_cookie_max_valid_minutes = this.secureSetting.cookie_max_valid_minutes
    // this.tempData.secureSetting_page_max_quiet_minutes = this.secureSetting.page_max_quiet_minutes
}

  getFormData(appStoreConfigs) {
    const data = {}
    appStoreConfigs.forEach(config => {
      if (config.sys_key === 'DeepinAppStoreSourceList') {
        console.log(config.sys_value);
        data[config.sys_key] = JSON.parse(config.sys_value)
      } else {
        data[config.sys_key] = config.sys_value;
      }
    });
    console.log('data', data);
    return data;
  }

  convertMetaData(formData) {
    const data = [];
    for (const key in formData) {
      const cell = {};
      if (Object.prototype.hasOwnProperty.call(formData, key)) {
        if (key === 'DeepinAppStoreSourceList') {
          cell['sys_value'] = JSON.stringify(formData[key]);
        } else {
          cell['sys_value'] = formData[key];
        }
        cell['sys_key'] = key;
      }
      data.push(cell);
    }
    return data;
  }

	async submit() {
		const value: Platformsettings = this.repoForm.value;
    const data = this.convertMetaData(value);
    console.log('data', data, JSON.stringify({configs: data}));
    const formData = new FormData();
    formData.append('configs', JSON.stringify(data));
    console.log('JSON.stringify(data)', JSON.stringify(data));
    await this.platformsetting.patchAppStore(formData);
		this.toaster.success('保存成功');
		setTimeout(() => {
      this.reload();
      this.repoForm.markAsUntouched();
		}, 500)
  }

	async sync() {
		await this.platformsetting.sync();
		this.toaster.success('已同步');
	}

	reload() {
		this.router.navigated = false;
		this.router.navigate([], { queryParamsHandling: 'merge' });
	}
}
